import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import jsPDF from 'jspdf'
import 'jspdf-autotable'

/**
 * Excel导出
 * @param {Array} data 导出数据
 * @param {Array} header 表头
 * @param {String} fileName 文件名
 */
export function exportExcel(data, header, fileName) {
  const ws = XLSX.utils.json_to_sheet(data, { header })
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([wbout], { type: 'application/octet-stream' })
  FileSaver.saveAs(blob, `${fileName}.xlsx`)
}

/**
 * Excel导入
 * @param {File} file 文件对象
 * @returns {Promise} 解析后的数据
 */
export function importExcel(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'array' })
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        const results = XLSX.utils.sheet_to_json(worksheet)
        resolve(results)
      } catch (error) {
        reject(error)
      }
    }
    reader.readAsArrayBuffer(file)
  })
}

/**
 * PDF导出
 * @param {Array} data 导出数据
 * @param {Array} columns 列配置
 * @param {String} fileName 文件名
 * @param {Object} options 配置项
 */
export function exportPDF(data, columns, fileName, options = {}) {
  const doc = new jsPDF(options)
  
  // 添加标题
  if (options.title) {
    doc.setFontSize(16)
    doc.text(options.title, 14, 15)
    doc.setFontSize(10)
  }

  // 转换数据格式
  const tableData = data.map(item => 
    columns.map(col => item[col.prop] || '')
  )

  // 生成表格
  doc.autoTable({
    head: [columns.map(col => col.label)],
    body: tableData,
    startY: options.title ? 25 : 15,
    ...options.table
  })

  // 保存文件
  doc.save(`${fileName}.pdf`)
}

/**
 * 下载模板
 * @param {Array} header 表头
 * @param {String} fileName 文件名
 */
export function downloadTemplate(header, fileName) {
  const ws = XLSX.utils.aoa_to_sheet([header])
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Template')
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([wbout], { type: 'application/octet-stream' })
  FileSaver.saveAs(blob, `${fileName}_template.xlsx`)
}